package org.neframework.webtest.action_rest;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.neframework.webtest.model.t_fk_file;
import org.neframework.webtest.util.file.FileTools;

import com.tmsps.neframework.jpa.sql.OrmComponent;

public class UploadTools {

	public static Map<String, String> upload(HttpServletRequest req,
			OrmComponent oc) {
		Map<String, String> result = new HashMap<String, String>();

		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();

		// Configure a repository (to ensure a secure temp location is used)
		ServletContext servletContext = req.getServletContext();
		File repository = (File) servletContext
				.getAttribute("javax.servlet.context.tempdir");
		factory.setRepository(repository);

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		// Parse the request
		List<FileItem> items = null;
		try {
			items = upload.parseRequest(req);
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Iterator<FileItem> iter = items.iterator();

		t_fk_file tf = null;
		while (iter.hasNext()) {
			FileItem item = iter.next();

			if (item.isFormField()) {
				// 非文件上传字段
				try {
					result.put(item.getFieldName(), item.getString("utf-8"));
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				continue;
			} else {
				tf = FileTools.processUploadedFile(req.getRealPath("/")
						+ File.separator + "data" + File.separator, item, oc);
			}
		}
		if (tf != null) {
			// 发送保存结果
			String url = req.getContextPath() + "/rest/download/" + tf.getKid()
					+ ".htm";

			result.put("success", true + "");
			result.put("file_id", tf.getKid());
			result.put("url", url);
			result.put("file_name", tf.getFile_name());
			result.put("content_type", tf.getContent_type());

		} else {
			result.put("success", false + "");
		}
		return result;
	}

}
